<script setup lang="ts">
import { ref } from 'vue'
import { useStore } from '@/stores'
import type { IOrder, IOrderItem } from '@/types/order'
import { saveReviewAPI, getReviewByIdAPI } from '@/services/review'
import { onLoad } from '@dcloudio/uni-app'
import { formatChineseJson, formateStr } from '@/utils/http'
import { useReview, useMemberStore } from '@/stores'
import type { Iform, IbyIdParams } from '@/types/review'
const { getReviewData, setReviewData } = useReview()
const { getUserInfo } = useMemberStore()

const query = defineProps<{
  orderId: number
  storeId: number
  reviewId: number
}>()

const reviewIdRequest = async () => {
  if (!query.reviewId) {
    return
  }
  const res = await getReviewByIdAPI({
    reviewId: query.reviewId,
    storeId: query.storeId,
    orderId: query.orderId,
  })
  form.value = res.data as Iform
  setReviewData(form.value?.orderItemList || [])
  form.value = { ...form.value, goodsList: getReviewData() } as Iform
}

onLoad(() => {
  reviewIdRequest()
})

const formRef = ref<UniHelper.UniFormsInstance>()

const form = ref({
  storeId: query.storeId,
  orderId: query.orderId,
  userId: getUserInfo()?.id,
  goodsList: getReviewData()?.map((item): IOrderItem => {
    return { ...item, likeStatus: 0, storeId: query.storeId, userId: getUserInfo()?.id || null }
  }),
  dishTasteRating: 0,
  mealSpeedRating: 0,
  serviceRating: 0,
  images: [],
  reviewText: '',
} as Iform)
// 定义校验规则
const rules: UniHelper.UniFormsRules = {
  reviewText: {
    rules: [
      { required: true, errorMessage: '请描述此次的用餐感受，以便于商家对您更好的服务！（必填）' },
    ],
  },
}

// 修改头像
const onImagesChange = () => {
  // 调用拍照/选择图片
  uni.chooseMedia({
    // 文件个数
    count: 1,
    // 文件类型
    mediaType: ['image'],
    success: (res) => {
      // 本地路径
      const { tempFilePath } = res.tempFiles[0]
      // 文件上传
      uni.uploadFile({
        url: '/oss/file/upload',
        name: 'file', // 后端数据字段名
        filePath: tempFilePath, // 新头像
        success: (res) => {
          // 判断状态码是否上传成功
          if (res.statusCode === 200) {
            // 提取头像
            const { url } = JSON.parse(res.data).data
            // // 当前页面更新头像
            form.value.images = [...form.value.images, url]
            // // 更新 Store 头像
            // memberStore.userInfo!.avatarUrl = url
            uni.showToast({ icon: 'success', title: '更新成功' })
          } else {
            uni.showToast({ icon: 'error', title: '出现错误' })
          }
        },
      })
    },
  })
}

const likedhander = (item: IOrderItem) => {
  if (query.reviewId) {
    return
  }
  item.likeStatus = item.likeStatus ? 0 : 1
}

const onSubmit = async () => {
  console.log(query.storeId)
  console.log(form.value)
  const result = await formRef.value?.validate?.()
  const res = await saveReviewAPI(form.value)
  uni.$emit('emitUpdateReviewId', { orderId: query.orderId, reviewId: res.data }) // 通知列表页更新数据
  // 返回上一页
  uni.navigateBack()
}
</script>

<template>
  <view class="review-page">
    <scroll-view class="review-container" scroll-y>
      <uni-forms :rules="rules" :model="form" ref="formRef">
        <uni-forms-item name="receiver" class="form-item">
          <view class="product-info" v-for="goodsItem in form.goodsList" :key="goodsItem.id">
            <image class="product-image" :src="goodsItem.image" mode="aspectFill"></image>
            <view class="product-con">
              <text class="title">{{ goodsItem.goodsName }}</text>
              <view class="con">
                <rich-text :nodes="formateStr(goodsItem)"></rich-text>
              </view>
            </view>
            <view class="product-praise" @click="likedhander(goodsItem)">
              <text class="iconfont icon-praise" v-if="!goodsItem.likeStatus"></text>
              <text class="iconfont icon-praise_fill" v-else></text>
            </view>
          </view>
        </uni-forms-item>

        <!-- Rating Section -->
        <uni-forms-item name="ratingList" class="form-item">
          <view class="rating-section">
            <view class="rating-item">
              <text class="rating-label">菜品口味</text>
              <uni-rate v-model="form.dishTasteRating" :readonly="query.reviewId"></uni-rate>
            </view>
            <view class="rating-item">
              <text class="rating-label">出餐速度</text>
              <uni-rate v-model="form.mealSpeedRating" :readonly="query.reviewId"></uni-rate>
            </view>
            <view class="rating-item">
              <text class="rating-label">服务态度</text>
              <uni-rate v-model="form.serviceRating" :readonly="query.reviewId"></uni-rate>
            </view>
          </view>
        </uni-forms-item>

        <!-- Review Text Area -->
        <uni-forms-item name="ratingList" class="form-item">
          <view class="review-textarea">
            <textarea
              class="textarea"
              :disabled="query.reviewId"
              placeholder="请描述此次的用餐感受，以便于商家对您更好的服务！（必填）"
              v-model="form.reviewText"
              :maxlength="200"
              :auto-height="false"
              placeholder-style="{ color: '#9CA3AF' }"
            ></textarea>
          </view>
        </uni-forms-item>

        <uni-forms-item name="ratingList" class="form-item">
          <!-- Photo Upload -->
          <view class="photo-upload">
            <view class="img-list">
              <view class="upload-btn" @click="onImagesChange" v-if="!query.reviewId"
                ><uni-icons type="camera-filled" size="24" color="#6B7280"></uni-icons
                ><text class="text">添加图片</text></view
              >
              <view class="upload-btn" v-for="(itemImageUrl, index) in form.images" :key="index">
                <image :src="itemImageUrl" mode="scaleToFill" />
              </view>
            </view>
            <text class="tip">最多上传9张图片</text>
          </view>
        </uni-forms-item>
      </uni-forms>

      <!-- <view class="flavor">
        <text class="tag">美味可口</text>
        <text class="tag">美味可口</text>
        <text class="tag">美味可口</text>
        <text class="tag">美味可口</text>
        <text class="tag">美味可口</text>
        <text class="tag">美味可口</text>
        <text class="tag">美味可口</text>
        <text class="tag">美味可口</text>
        <text class="tag">美味可口</text>
      </view> -->
    </scroll-view>
    <!-- Submit Button -->
    <view class="submit-button" v-if="!query.reviewId">
      <button class="submit-btn" @click="onSubmit">发布评价</button>
    </view>
  </view>
</template>

<style lang="scss">
@import '@/styles/variables.scss';

page {
  height: 100%;
  overflow: hidden;
}

.review-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: $background-color;
  .review-container {
    flex: 1;
  }

  .product-info {
    display: flex;
    align-items: center;
    padding: 32rpx;
    background-color: #fff;
    margin-bottom: 32rpx;

    .product-image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 24rpx;
      margin-right: 10rpx;
    }

    .product-con {
      flex: 1; // Take up remaining space
      margin-right: 10rpx;
      display: flex;
      flex-direction: column;

      .title {
        font-size: 32rpx;
        font-weight: $font-medium-weight;
        color: $good-font-title-color;
        margin-bottom: 10rpx;
      }

      .con {
        font-size: $font-size;
        color: $good-font-con-color;
        font-weight: $font-weight;
      }
    }

    .product-praise {
      .iconfont {
        color: #ccc; // Default color
        &.icon-praise_fill {
          color: #ff6600; // Filled praise icon color
        }
      }
    }
  }

  .review-textarea {
    padding: 32rpx;
    width: 100%;
    box-sizing: border-box;
    background-color: #fff;

    .textarea {
      width: 100%;
      padding: 32rpx;
      background-color: $background-color;
      box-sizing: border-box;
      border: 1px solid #ccc;
      border-radius: 24rpx;
      font-size: $font-medium-size;
      color: $good-font-title-color;
    }
  }

  .photo-upload {
    padding: 32rpx;
    display: flex;
    flex-direction: column;
    .tip {
      margin-top: 20rpx;
      font-size: $font-size;
      font-weight: $font-weight;
      color: $good-font-con-color;
    }

    .img-list {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      // justify-content: flex-start;
      /* 让元素在交叉轴上从起始位置开始排列 */
      // align-items: flex-start;
      /* 设置元素之间的间距 */
      gap: 16rpx;
      .upload-btn {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 168rpx;
        height: 168rpx;
        border-radius: 24rpx;
        border: 1px dashed #ccc;
        .text {
          font-size: $font-size;
          color: $good-font-con-color;
        }
      }
    }
  }

  .rating-section {
    padding: 32rpx;
    background-color: #fff;

    .rating-item {
      display: flex;
      align-items: center;
      margin-bottom: 10rpx;
      justify-content: space-between;

      .rating-label {
        margin-right: 10rpx;
        font-size: $font-medium-size;
        font-weight: $font-weight;
        color: $good-font-title-color;
      }
    }
  }

  .flavor {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    gap: 16rpx;
    padding: 32rpx;
    .tag {
      font-size: $font-size;
      font-weight: $font-weight;
      color: $color;
      height: 76rpx;
      line-height: 76rpx;
      text-align: center;
      padding: 0 32rpx;
      border-radius: 38rpx;
      border: 1px solid $color;
    }
  }

  .submit-button {
    padding: 32rpx;

    .submit-btn {
      width: 100%;
      height: 96rpx;
      background-color: $color;
      color: white;
      border: none;
      border-radius: 43rpx;
      font-size: $font-medium-size;
      line-height: 96rpx;
      text-align: center;
    }
  }
}
</style>
